package com.dd.census.tools.validator;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

public class ValidateUtil {
	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	public static <T> ValidationResult validate(T obj) {
		ValidationResult result = new ValidationResult();
		Set<ConstraintViolation<T>> set = validator.validate(obj);
		if (null != set && set.size() > 0) {
			result.setHasErrors(true);
			String errorMsg ="";
			for (ConstraintViolation<T> cv : set) {
				errorMsg = cv.getMessage();
				continue;
			}
			result.setCode(-1);
			result.setErrorMsg(errorMsg);
		} else {
			result.setCode(0);
			result.setHasErrors(false);
		}
		return result;
	}

	public static <T> ValidationResult validateProperty(T obj, String propertyName) {
		ValidationResult result = new ValidationResult();
		Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName);
		if (null != set && set.size() > 0) {
			result.setHasErrors(true);
			String errorMsg ="";
			for (ConstraintViolation<T> cv : set) {
				errorMsg = cv.getMessage();
				continue;
			}
			result.setCode(-1);
			result.setErrorMsg(errorMsg);
		} else {
			result.setCode(0);
			result.setHasErrors(false);
		}

		return result;

	}
    private ValidateUtil() {}
	public static class ValidationResult {
		/**
		 * 校验结果是否有错,有验证错误=true 验证通过=false
		 */
		private boolean hasErrors;
		/**
		 * 校验错误信息
		 */
		private String errorMsg;
		
		/**
		 * 错误码
		 */
		private int code;

		public boolean isHasErrors() {
			return hasErrors;
		}

		public void setHasErrors(boolean hasErrors) {
			this.hasErrors = hasErrors;
		}

		public String getErrorMsg() {
			return errorMsg;
		}

		public void setErrorMsg(String errorMsg) {
			this.errorMsg = errorMsg;
		}

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		@Override
		public String toString() {
			return "ValidationResult [hasErrors=" + hasErrors + ", errorMsg=" + errorMsg+ ", code=" + code + "]";
		}
	}

}
